import "../static/libs/flexible"
import "../scss/common.scss"
import "../scss/errors.scss"
import http from "../utils/http"
//页码
let selectedIndex = 0
//控制是否有答案页面开关
let hasAnswerOrNot = true
//答案数组
let arr = []

//本地储存的学生id
const { _id } = JSON.parse(localStorage.getItem("userInfo") || "{}")
let exercises = []
async function main() {
    //通过学生id拿所有错题
    const data = await http({ url: "/errors/findByStuId?id=" + _id })
    exercises = data.data
    arr.length = exercises.length

    //渲染无答案
    renderNotHaveAnswer()

    //翻页
    fanye()

    //点击解析按钮 显示或隐藏解析
    displayAnalysis()

    //点击删除按钮
    deleteExercise()

    //点击重新复习 
    clickReview()

    //返回上一页
    backPage()
}
main()

//渲染有答案
function renderHasAnswer() {
    //答案转化的数据
    const str = ["A", "B", "B", "C"]
    $(".bigbox main").html(`
    <div class="title">
        <p>${exercises[selectedIndex].exerciseId.answer.length == 1 ? '单选题' : '多选题'}</p>
        <span>${exercises[selectedIndex].exerciseId.topics}</span>
    </div>
    <div class="option">
        <input type="radio" name="name"><label>${exercises[selectedIndex].exerciseId.options[0]}</label><br>
        <input type="radio" name="name"><label>${exercises[selectedIndex].exerciseId.options[1]}</label><br>
        <input type="radio" name="name"><label>${exercises[selectedIndex].exerciseId.options[2]}</label><br>
        <input type="radio" name="name"><label>${exercises[selectedIndex].exerciseId.options[3]}</label><br>
    </div>
    <div class="answer">
        <p>正确答案: ${str[exercises[selectedIndex].exerciseId.answer[0]]}</p>
        <p>答案解析：${exercises[selectedIndex].exerciseId.analysis}</p>
    </div>
    `)
    //右下角题数渲染
    renderExercisesCounts(exercises)
    //渲染之前选中的答案
    renderChoosedAnswer(exercises)
    $("main .answer").css("display", "block")
}

//翻页
function fanye() {
    //第一次触碰的焦点 ，最后触碰的焦点 ，滑动距离
    let startX, endX, dis = 0;
    //获取第一次触碰屏幕的焦点startx的事件
    document.addEventListener('touchstart', function (e) {
        var touch = e.touches[0];
        startX = touch.pageX;
    })

    //获取最后触摸的焦点endx , 算出滑动屏幕的距离dis的事件
    document.addEventListener('touchmove', function (e) {
        var touch = e.touches[0];
        endX = touch.pageX;
        dis = startX - endX;
    })

    //滑动事件结束 如果手指滑动距离大于200 并且正向则执行pageTop函数 -->向上滑动翻页
    //滑动事件结束 如果手指滑动距离大于200 方向为负则执行pageDown函数 -->向下滑动翻页
    //翻页完毕 执行qingling函数 进行数值清零
    document.addEventListener('touchend', function (e) {
        //Math.abs 返回绝对值
        if (Math.abs(dis) > 200) {
            if (dis > 0) {
                if (selectedIndex >= exercises.length - 1) alert("这是最后一题")
                else {
                    //渲染下一题
                    selectedIndex++
                    //答案无
                    renderNotHaveAnswer()

                }
            } else {
                if (selectedIndex <= 0) alert("这是第一题")
                else {
                    //渲染上一题
                    selectedIndex--
                    //答案无
                    renderNotHaveAnswer()
                }
            }
        }
        //归零
        reset()
    })
    //坐标归零
    function reset() {
        startX = 0
        endX = 0
        dis = 0
    }

    //翻页点击事件
    //下一页
    $("header .sp2").on("click", function () {
        if (selectedIndex >= exercises.length - 1) alert("这是最后一题")
        else {
            //渲染下一题
            selectedIndex++
            //答案无
            renderNotHaveAnswer()
        }
        //归零
        reset()
    })
    //上一页
    $("header .sp1").on("click", function () {
        if (selectedIndex <= 0) alert("这是第一题")
        else {
            //渲染上一题
            selectedIndex--
            //渲染题目信息
            //答案无
            renderNotHaveAnswer()
        }
        //归零
        reset()
    })
}

//右下角题数渲染
function renderExercisesCounts() {
    $("footer .four span").html(`
    <strong>${selectedIndex + 1}</strong>/${exercises.length}
    `)
    //渲染题目列表
    renderExercisesList(exercises)
}

//渲染之前选中的答案
function renderChoosedAnswer() {
    //循环数组，查看是否有值
    if (exercises[selectedIndex].errorAnswer[0] != undefined) {
        //控制单选框选中状态
        $("main .option [name=name]").eq(exercises[selectedIndex].errorAnswer[0]).attr("checked", "checked")
        //控制选中答案字体颜色
        $("main .option label").eq(exercises[selectedIndex].errorAnswer[0]).css("color", "#6966eb")
    }
}

//点击右下角题数弹出题目列表
function renderExercisesList() {
    $("footer .four").on("click", function () {
        $(".grayy").css("display", "block")
        $(".grayy .four span").html(`<strong>${selectedIndex + 1}</strong>/${exercises.length}`)
        $(".grayy .danxuan p").html(`单选题(共${exercises.length}题,合计${exercises.length * 3}分)`)
        //渲染题号
        renderExerciseNumber(exercises)
        //滑动隐藏题目列表
        displayExercisesList()
    })
}

//滑动或点击隐藏题目列表
function displayExercisesList() {
    let startY, endY, disss = 0
    //获取第一次触碰屏幕的焦点startY的事件
    document.addEventListener('touchstart', function (e) {
        var touch = e.touches[0];
        startY = touch.pageY;
    })

    //获取最后触摸的焦点endY , 算出滑动屏幕的距离dis的事件
    document.addEventListener('touchmove', function (e) {
        var touch = e.touches[0];
        endY = touch.pageY;
        disss = startY - endY;
    })

    document.addEventListener('touchend', function (e) {
        //Math.abs 返回绝对值
        if (Math.abs(disss) > 200) {
            if (disss > 0) {

            } else {
                $(".grayy .list").addClass("fade")
                setTimeout(function () {
                    $(".grayy .list").removeClass("fade")
                    $(".grayy").css("display", "none")
                }, 300)
            }
        }
        //清零
        resetList()
    })
    //清零
    function resetList() {
        startY = 0
        endY = 0
        disss = 0
    }

    $(".grayy .on .three p").on("click", function () {
        $(".grayy .list").addClass("fade")
        setTimeout(function () {
            $(".grayy .list").removeClass("fade")
            $(".grayy").css("display", "none")
            resetList()
        }, 300)
    })
}

//渲染题号
function renderExerciseNumber() {
    let tempArr = ``
    for (let i = 0; i < exercises.length; i++) {
        //判断该题是否被收藏
        tempArr += `<div class="one"> ${i + 1} </div>`
    }
    $(".grayy .danxuan .tihao").html(tempArr)
    if (!hasAnswerOrNot) {
        //控制题目列表的题对错状态
        controlExercisesListState(exercises)
        //控制题目列表的题已做未做状态
        controlReviewExercisesListState()
    }
    //点击题目列表的题号，定位到该题
    clickExerciseNumLocate(exercises)
}

//控制题目列表的题对错状态
function controlExercisesListState() {
    if (!arr.includes(undefined)) {
        for (let i = 0; i < exercises.length; i++) {
            if (arr[i] != exercises[i].exerciseId.answer[0]) {
                $(".grayy .danxuan .one").eq(i).addClass("errorAnswer")
            } else $(".grayy .danxuan .one").eq(i).removeClass("errorAnswer")
        }
    }
}

//点击题目列表的题号，定位到该题
function clickExerciseNumLocate() {
    $(".grayy .danxuan .one").on("click", function () {
        //调用渲染题的方法，参数为题目对象参数
        selectedIndex = $(this).text().trim() - 1
        //控制题目列表的页码
        $(".grayy .four span").html(`<strong>${selectedIndex + 1}</strong>/${exercises.length}`)
        $(".grayy .danxuan p").html(`单选题(共${exercises.length}题,合计${exercises.length * 3}分)`)
        //渲染题目信息
        //答案无
        renderNotHaveAnswer(exercises)
    })
}

//点击解析按钮 显示或隐藏解析
function displayAnalysis() {
    //底部解析  ||  题目列表解析
    $("footer .one , .grayy .on .one").on("click", function () {

        if ($("main .answer").css("display") == "block") {
            $("main .answer").removeClass("analysisFade2")
            $("main .answer").addClass("analysisFade1")
            setTimeout(function () {
                $("main .answer").css("display", "none")
            }, 300)
        } else {
            $("main .answer").removeClass("analysisFade1")
            $("main .answer").addClass("analysisFade2")
            setTimeout(function () {
                $("main .answer").css("display", "block")
            }, 300)
        }
    })
}


//点击删除按钮
function deleteExercise() {
    $("footer .two , .grayy .on .two").on("click", async function () {
        const id = exercises[selectedIndex]._id
        //向后端发送错题id
        const res = await http({ url: "/errors/deleteById?id=" + id })
        console.log(res);
        if (res.code == 1) {
            selectedIndex = 0
            const data2 = await http({ url: "/errors/findByStuId?id=" + _id })
            exercises = data2.data
            arr.length = exercises.length
            //重新渲染
            renderNotHaveAnswer()
        }
    })
}

//点击重新复习
function clickReview() {
    if ($("footer .three p").text() == "重新复习") {
        $("footer .three p").on("click", function () {
            //渲染无答案 （重新做题
            selectedIndex = 0
            //渲染无答案 （重新做题）
            renderNotHaveAnswer(exercises)
            //点击提交按钮
            //clickSubmit(exercises)
        })
    }
}

//渲染无答案
function renderNotHaveAnswer() {
    //答案转化的数据
    const str = ["A", "B", "B", "C"]
    $(".bigbox main").html(`
    <div class="title">
        <p>${exercises[selectedIndex].exerciseId.answer.length == 1 ? '单选题' : '多选题'}</p>
        <span>${exercises[selectedIndex].exerciseId.topics}</span>
    </div>
    <div class="option">
        <input type="radio" value="A" name="name"><label>${exercises[selectedIndex].exerciseId.options[0]}</label><br>
        <input type="radio" value="B" name="name"><label>${exercises[selectedIndex].exerciseId.options[1]}</label><br>
        <input type="radio" value="C" name="name"><label>${exercises[selectedIndex].exerciseId.options[2]}</label><br>
        <input type="radio" value="D" name="name"><label>${exercises[selectedIndex].exerciseId.options[3]}</label><br>
    </div>
    <div class="answer">
        <p>正确答案: ${str[exercises[selectedIndex].exerciseId.answer[0]]}</p>
        <p>答案解析：${exercises[selectedIndex].exerciseId.analysis}</p>
    </div>
    `)
    //渲染之前选中的答案
    renderReviewAnswer()
    //右下角题数渲染
    renderExercisesCounts(exercises)
    //获取选中的答案
    chooseAnswer()
}

//获取选中的答案
function chooseAnswer() {
    $("main .option [name=name]").on("change", function () {
        const res = $("main .option [name=name]:checked").val()
        if (res == "A") {
            arr[selectedIndex] = 0
        } else if (res == "B") {
            arr[selectedIndex] = 1
        } else if (res == "C") {
            arr[selectedIndex] = 2
        } else if (res == "D") {
            arr[selectedIndex] = 3
        }
        $("main .answer").removeClass("analysisFade1")
        $("main .answer").addClass("analysisFade2")
        setTimeout(function () {
            $("main .answer").css("display", "block")
        }, 300)
    })
}

//渲染之前选中的答案
function renderReviewAnswer() {
    //查看是否有值
    if (arr[selectedIndex] != undefined) {
        $("main .option [name=name]").eq(arr[selectedIndex]).attr("checked", "checked")
        $("main .answer").css("display", "block")
    }
}

//点击提交按钮
function clickSubmit() {
    if ($("footer .three p").text() == "提交答案") {
        $("footer .three p").on("click", async function () {
            //判断题是否答完
            if (arr.includes(undefined) || arr.length != exercises.length) {
                //没有答完提示用户 （显示提示窗口
                $(".gray").css("display", "block")
                //点击继续答题隐藏提示窗口
                $(".gray #cancel").on("click", function () {
                    $(".gray").css("display", "none")
                })
            } else {
                //对比答案，显示结果
                let rightAnswer = [] //正确答案
                console.log(arr);
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i] == exercises[i].exerciseId.answer[0]) {
                        rightAnswer.push(exercises[i]._id)
                    }
                }
                //显示弹框
                $(".submit").css("display", "block")
                //渲染正确答案数量
                $(".submit .p2 span").text(rightAnswer.length)
                //渲染错误答案数量
                $(".submit .p3 span").text(exercises.length - rightAnswer.length)

                //取消删除错题，重新渲染有答案页面
                $(".submit .two #cancel").on("click", function () {
                    $(".submit").css("display", "none")
                    $("footer .three p").text("重新复习")
                    //页码
                    selectedIndex = 0
                    //控制解析
                    analysisState = true
                    //控制是否有答案页面开关
                    hasAnswerOrNot = true
                    //重新渲染无答案的题目信息
                    renderNotHaveAnswer()
                })

                //点击确认按钮
                $(".submit .two #confirm").on("click", async function () {
                    $(".submit").css("display", "none")
                    if (rightAnswer.length) {
                        console.log(rightAnswer);
                        //向后端发送正确题数组
                        const res = await http({ url: "/errors/deleteByArray", method: "POST", data: { arr: JSON.stringify(rightAnswer) } })
                        //重新渲染
                        main()
                    }
                })
            }
        })
    }
}

//控制题目列表的题已做未做状态
function controlReviewExercisesListState() {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] != undefined) $(".grayy .danxuan .one").eq(i).removeClass("notChoose")
        else $(".grayy .danxuan .one").eq(i).addClass("notChoose")
    }
}

//点击返回上一页面
function backPage() {
    $("header img").on("click", function(){
        window.history.back()
    })
}